package org.kfive.nova.web.controllers;

/*
 * Copyright (c) 2016 lizhanwu.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.context.request.async.WebAsyncTask;

import java.util.concurrent.Callable;

/*
 * <p>
 * AsyncController.java
 *
 * Application:
 * NO
 *
 * Limited:
 * NO
 *
 * Warning:
 * NO
 *-----------------------------------------------------------------------------
 *         VERSION       DATE            BY       CHANGE/COMMENT
 * -----------------------------------------------------------------------------
 *          1.0      2016-8-1216:44     lizhanwu      create
 * -----------------------------------------------------------------------------
 * </p>
 */
@Controller
@RequestMapping("aysn")
public class AsyncController {

    @RequestMapping("/response-body")
    public @ResponseBody Callable<String> callable(final @RequestParam(required=false, defaultValue="true") boolean handled) {
        //进行一些与处理之后，把最耗时的业务逻辑部分放到Callable中，注意，如果你需要在new Callable中用到从页面传入的参数，需要在参数前加入final
        return new Callable<String>() {
            public String call() throws Exception {
                if(handled){
                    Thread.sleep(2000);
                }else{
                    Thread.sleep(2000*2);
                }
                return "Callable result";
            }
        };
    }

    @RequestMapping("deferred")
    @ResponseBody
    public DeferredResult<String> deferredTest(){
        DeferredResult<String> deferredResult = new DeferredResult<String>();
        return deferredResult;
    }

    @RequestMapping("task")
    @ResponseBody
    public WebAsyncTask<String> webAsyncTask(){
        Callable<String> callable = new Callable<String>() {
            public String call() throws Exception {
                Thread.sleep(5000);
                return "task";
            }
        };
        WebAsyncTask<String> webAsyncTask = new WebAsyncTask<String>(6000,callable);
        webAsyncTask.onTimeout(new Callable<String>() {
            public String call() throws Exception {
                return "timeout";
            }
        });
        return webAsyncTask;
    }

}
